package main

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/reflection/grpc_reflection_v1"
	"log"
)

func main() {
	conn, err := grpc.Dial("127.0.0.1:8888", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		panic(err)
	}

	clientV1 := grpc_reflection_v1.NewServerReflectionClient(conn)
	stream, err := clientV1.ServerReflectionInfo(context.Background(), grpc.WaitForReady(true))
	if err != nil {
		log.Fatalf("cannot get ServerReflectionInfo: %v", err)
	}
	testListServices(stream)
}

func testListServices(stream grpc_reflection_v1.ServerReflection_ServerReflectionInfoClient) {
	if err := stream.Send(&grpc_reflection_v1.ServerReflectionRequest{
		MessageRequest: &grpc_reflection_v1.ServerReflectionRequest_ListServices{},
	}); err != nil {
		log.Fatalf("failed to send request: %v", err)
	}
	r, err := stream.Recv()
	if err != nil {
		// io.EOF is not ok.
		log.Fatalf("failed to recv response: %v", err)
	}

	switch r.MessageResponse.(type) {
	case *grpc_reflection_v1.ServerReflectionResponse_ListServicesResponse:
		services := r.GetListServicesResponse().Service
		for _, e := range services {
			fmt.Println("service name: ", e.Name)
		}
	default:
		log.Fatalf("ListServices = %v, want type <ServerReflectionResponse_ListServicesResponse>", r.MessageResponse)
	}
}
